package com.jhm.bing_fa_rong_qi;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class ArrayBlockingQueueExample {
    public static void main(String[] args) {
        // 创建一个容量为5的ArrayBlockingQueue
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);

        // 生产者线程
        Thread producer = new Thread(() -> {
            try {
                while(true){
                    TimeUnit.SECONDS.sleep(1);
                    System.err.println(Thread.currentThread().getName()+"已出餐");
                    queue.put("meat"); // 队列满了会阻塞
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                while(true) {
                    String item = queue.take(); // 队列为空会阻塞
                    System.out.println(Thread.currentThread().getName()+"已取餐");
                    TimeUnit.SECONDS.sleep(2);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        for(int i=0;i<6;i++){
            new Thread(producer,"producer"+i).start();
        }
        for(int i=0;i<10;i++){
            new Thread(consumer,"consumer"+i).start();
        }
    }
}